const defaultwWhiteRouters: any[] = ["/oauth-login", "/", "login"];

const defaultActiveRules: any[] = [];
const formartActiveRules = (activeRules: any[]) => {
    let _activeRules = []
    for (let index = 0; index < activeRules.length; index++) {
        const _activeRule = activeRules[index];
        if(typeof _activeRule === 'string'){
            _activeRules.push(_activeRule)
        }else if(typeof _activeRule === 'object'){
            _activeRule.forEach((p: string)=>{
                _activeRules.push(p)
            })
        }
    }
    return _activeRules

}
// 判断匹配规则是否重复，重复需要去掉一个(存在一种特殊情况，重复后，第一个匹配部分规则丢失（权限系统）)
export function checkActiveRule(pullPath: string, activeRules: any[]) {
  let path = pullPath;
  for (let index = 0; index < activeRules.length; index++) {
    const activeRule = activeRules[index];
    const regex = new RegExp(activeRule, "g");
    const count = (pullPath.match(regex) || []).length;
    if (count > 1) {
      // path = path.replace(activeRule, "");
      const hasIndex = path.lastIndexOf(activeRule)
      path = path.substring(hasIndex)
      break;
    }
  }
  return path;
}

class HistoryMemory {
  limit: number;
  urls: string[];
  whiteRouters: string[];
  activeRules: string[];
  constructor(props: { [x: string]: any }) {
    const {
      limit = 10,
      whiteRouters = defaultwWhiteRouters,
      activeRules = defaultActiveRules,
    } = props;
    // 白名单
    this.whiteRouters = whiteRouters;
    // 存储历史上限
    this.limit = limit;
    // 存储历史数据
    this.urls = [];
    // 存储匹配规则数据
    this.activeRules = formartActiveRules(activeRules);
  }
  // 历史数据更新
  updateByLRU(index: number, pullPath: string) {
    if (index > -1) {
      this.urls.splice(index, 1);
      this.urls.push(pullPath);
    }
  }
  // 添加历史
  push(pullPath: string, replace = true) {
    // 存储原始数据一份
    const oldPullPath = pullPath;
    // 判断匹配规则是否重复，重复需要去掉一个
    pullPath = checkActiveRule(pullPath, this.activeRules);
    // 白名单不添加
    if (this.whiteRouters.includes(pullPath)) {
      return null;
    }
    // 存在历史（LRU更新历史数据）
    // 1：全匹配存在，2：出掉重复activeRule后存在
    if (this.urls.includes(pullPath)) {
      let returnPath = null;
      // 情况2
      if (!this.urls.includes(oldPullPath)) {
        returnPath = pullPath;
        // 重写当前错误的history信息
        if(replace){
          history.replaceState({ ...history.state, current: returnPath }, ""); 
        }
      }
      let hasIndex = this.urls.findIndex((url: string) => url === pullPath);
      this.updateByLRU(hasIndex, pullPath);
      return returnPath;
    }
    // 不存在（判断是否超限，超限删除最老的数据）
    // 不存在存在2种，一种activeRule丢失，只保留了子应用路由
    // 一种是完整数据，且是最新的路由数据
    let hasPartIndex = this.urls.findIndex(
      (url: string) => url.indexOf(pullPath) > 0
    );

    if (hasPartIndex > -1) {
      // activerule信息丢失
      let _pullPath = this.urls[hasPartIndex];
      // this.updateByLRU(hasPartIndex, _pullPath)
      // 重写当前错误的history信息
      if(replace){
        history.replaceState({ ...history.state, current: _pullPath }, "");
      }
      return _pullPath;
    } else {
      if (this.urls.length >= this.limit) {
        this.updateByLRU(0, pullPath);
      } else {
        this.urls.push(pullPath);
      }
      return null;
    }
  }
}

export default HistoryMemory;
